<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="区域名称" prop="areaName">
        <el-input
          v-model="queryParams.areaName"
          placeholder="请输入区域名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['kindergarten:environmentInfo:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['kindergarten:environmentInfo:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['kindergarten:environmentInfo:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['kindergarten:environmentInfo:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row> -->

    <el-table
      v-loading="loading"
      :data="environmentInfoList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备id" align="center" prop="id" /> -->
      <el-table-column label="区域名称" align="center" prop="areaName" />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="设备运行状态" align="center" prop="deviceStatus">
        <template #default="scope">
          <dict-tag :options="device_status" :value="scope.row.deviceStatus" />
        </template>
      </el-table-column>
      <el-table-column label="指标" align="center">
        <template #default="scope">
          <div
            :id="'chart-' + scope.$index"
            style="width: 280px; height: 100px"
          ></div>
        </template>
      </el-table-column>
      

      <!-- <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['kindergarten:environmentInfo:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['kindergarten:environmentInfo:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改环境信息对话框 -->
    <!-- <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="environmentInfoRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup name="EnvironmentInfo">
import {
  listEnvironmentInfo,
  getEnvironmentInfo,
  delEnvironmentInfo,
  addEnvironmentInfo,
  updateEnvironmentInfo,
  getValue
} from "@/api/kindergarten/environmentInfo";
import { nextTick } from "vue";
import * as echarts from "echarts";
import { onMounted, onUnmounted,watch  } from 'vue'
import { ref } from "vue";

const { proxy } = getCurrentInstance();
const { device_status } = proxy.useDict("device_status");

const environmentInfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    areaName: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

const socket =  new WebSocket('ws://192.168.1.103/ws')
socket.onopen =()=>{
  console.log('成功');
}
socket.onmessage =(event)=>{
  console.log(event.data);
  monge(event.data)
}

socket.onclose = (event)=>{
  console.log("关闭",event.data);
}
socket.onerror = (event)=>{
  console.log('错误',event);
}
const monge = (data)=>{
  const jsonData = JSON.parse(data)
  environmentInfoList.value.map(item =>{
    if (jsonData.deviceName == item.deviceName) {
      item.deviceStatus = jsonData.deviceStatus
    }
  })
}


const iotSocket = new WebSocket('ws://192.168.1.103/ws/Iot')
iotSocket.onopen =()=>{
  
  console.log('iot成功');
}
iotSocket.onmessage =(event)=>{
  mongo(JSON.parse(event.data))
}
iotSocket.onclose = (event)=>{
  console.log("关闭",event.data);
}
iotSocket.onerror = (event)=>{
  console.log('错误',event);
}
const historyValuesList = ref(
  environmentInfoList.value.map(() => Array(10).fill(0))
);


watch(
  () => environmentInfoList.value.length,
  (newLength) => {
    // 当列表长度变化时，同步更新历史数据数组的长度
    while (historyValuesList.value.length < newLength) {
      historyValuesList.value.push(Array(10).fill(0));
    }
    historyValuesList.value = historyValuesList.value.slice(0, newLength);
  }
);
const mongo = (newValue) => {
  environmentInfoList.value.forEach((item, index) => {
    const chart = miniCharts.get(index);
    // 获取当前图表的历史数据（响应式）
    const values = historyValuesList.value[index];

    console.log(item.physical,1);
    console.log(newValue.physical,2)
    if (item.physical == newValue.physical) {
      // console.log(newValue.physical);

      // 匹配时，更新历史数据（移除第一个，添加新值）
      // 注意：Vue3 中修改数组需要用数组方法触发响应式更新
      values.shift();
      values.push(newValue.value);
      historyValuesList.value[index] = [...values];
      // 强制触发更新（因为 shift/push 会修改原数组，ref 数组的索引变化可能不被深层追踪）
    }

    // 更新图表数据（使用当前历史数据）
    chart.setOption({
      series: [{ data: [...values] }]
    });
  });
};




/** 查询环境信息列表 */
function getList() {
  loading.value = true;
  listEnvironmentInfo(queryParams.value).then((response) => {
    environmentInfoList.value = response.rows.map((item) => ({
      ...item,
      indicatorValues: Array.from({ length: 10 }, () =>
        (Math.random() * 100).toFixed(2)
      ),
    }));
    total.value = response.total;
    loading.value = false;
    nextTick(() => {
      drawMiniCharts();
    });
  });
}

const miniCharts = new Map();

async function fetchDeviceValue(deviceId) {
  try {
    // 调用接口，传入设备ID
    const response = await getValue(deviceId);
    // 后端直接返回 Double 数值（如 25.6），无需额外解析 data 字段
    const deviceValue = response; 

    // 打印结果（调试用）

    // 返回数值供后续使用（如更新图表）
    return deviceValue;
  } catch (error) {
    // 错误处理（如接口异常、网络问题）
    console.error(`获取设备${deviceId}数值失败：`, error);
    return null;  // 失败时返回 null，避免后续逻辑报错
  }
}
let option = {}

const handleKeyUp = (e) => {
   
}

const index = ref(0)

function drawMiniCharts() {
  environmentInfoList.value.forEach((item, index) => {
    const chartDom = document.getElementById("chart-" + index);
    if (!chartDom) return;
    // 若已存在图表则直接取
    let chart = miniCharts.get(index);
    if (!chart) {
      chart = echarts.init(chartDom);
      miniCharts.set(index, chart);
    }
    // 初始化数据
    let values = [0, 0, 0, 0, 0, 0,0,0,0,0];
    // 基础配置
const Maximum = [1600,100,80,1000,100]
 option = {
  grid: { 
    left: 50, // 增大左侧空间，给 Y 轴标签留位置
    right: 20, 
    top: 20, 
    bottom: 20 
  },
  xAxis: { 
    type: "category", 
    show: true, // 显示x轴便于对齐
    data: values.map((_, i) => i + 1) ,
  },
  yAxis: { 
    type: "value", 
    show: true, // 显示y轴便于对齐
    splitLine: { show: false },
     max: Maximum[index],
     axisLabel: {
      fontSize: 12, // 字体大小
      color: '#333', // 字体颜色
      formatter: '{value}', // 标签格式（也可自定义，如加单位）
    }
  },
  visualMap: {
    show: false,
    type: 'piecewise',
    dimension: 1,
    pieces: [
      { max: 800, color: '#67C23A' },
      { min: 801, max: 1000, color: '#E6A23C' },
      { min: 1001, color: '#F56C6C' }
    ],
    inRange: {
      lineStyle: { color: null },
      areaStyle: { color: null }
    }
  },
  series: [
    // 1. 折线系列：分段变色
    {
      data: values,
      type: "line",
      smooth: true,
      symbol: "none",
      lineStyle: { width: 2 },
      emphasis: { disabled: true },
    },
    // 2. 绿色垂直条（≤800）
    {
      data: values.map(item => item[1]),
      type: "bar",
      barWidth: 2,
      itemStyle: { color: '#67C23A' },
      visualMap: {
        show: false,
        type: 'piecewise',
        dimension: 0,
        pieces: [{ max: 800 }]
      }
    },
    // 3. 黄色垂直条（801-1000）
    {
      data: values.map(item => item[1]),
      type: "bar",
      barWidth: 2,
      itemStyle: { color: '#E6A23C' },
      visualMap: {
        show: false,
        type: 'piecewise',
        dimension: 0,
        pieces: [{ min: 801, max: 1000 }]
      }
    },
    // 4. 红色垂直条（≥1001）
    {
      data: values.map(item => item[1]),
      type: "bar",
      barWidth: 2,
      itemStyle: { color: '#F56C6C' },
      visualMap: {
        show: false,
        type: 'piecewise',
        dimension: 0,
        pieces: [{ min: 1001 }]
      }
    }
  ],
  tooltip: {
    show: true,
    trigger: "axis",
    // 增加tooltip的样式和内容优化
    backgroundColor: 'rgba(255, 255, 255, 0.9)', // 浅色背景，提升可读性
    borderColor: '#ddd',
    borderWidth: 1,
    textStyle: { color: '#333', fontSize: 13 }, // 深色文字，稍大字体
    padding: 10, // 内边距，避免内容拥挤
    formatter: function(params) {
      // 自定义tooltip内容，明确显示X和Y值
      let res = `第${params[0].name}个数据<br/>`;
      params.forEach(item => {
        // 只显示有效数据（避免重复）
        if (item.seriesType === 'line') {
          res += `${item.value}<br/>`;
        }
      });
      return res;
    }
  },
};
    chart.setOption(option);

    if(index != 0){
      if (!chart._interval) {
      chart._interval = setInterval(async () => {
        let random = 0
        if(index == 1){
          random = Math.floor(Math.random() * (50 -45  +1)  + 45)
        }else if(index == 2){
          random =  Math.floor(Math.random() * (40 - 30+ 1)  + 30)
        }else if (index == 3){
          random=  Math.floor(Math.random() * (500 - 450+ 1)  + 450)
        }else if(index == 4){
          random =  Math.floor(Math.random() * (24 - 21+ 1)  + 21)
        }
        values.shift();
        values.push(random);
        chart.setOption({
          series: [{ data: values }],
        });
      }, 1000);
    }
    }
    // 每隔 1 秒动态更新数据，模拟滚动
    
  });
}


/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

const handleKeyDown = (e) => {
  // 监听w键（keyCode 87 或 key为'w'/'W'）
  if (e.key.toLowerCase() === 'w') {
    // 若已存在图表则直接取
    let chart = miniCharts.get(0);
    if (index.value % 2 == 0){
      option = {
        visualMap: {
          pieces: [
            { max: 800, color: '#67C23A' },
            { min: 801, max: 1000, color: '#67C23A' },
            { min: 1001, color: '#67C23A' }
          ],
        },
        series:[

        ]
      }
      chart.setOption(option)
      console.log('w');
   }else{
    option = {
      visualMap: {
        pieces: [
          { max: 800, color: '#67C23A' },
          { min: 801, max: 1000, color: '#E6A23C' },
          { min: 1001, color: '#F56C6C' }
        ],
      },
    }
    chart.setOption(option)
    console.log('w22');
   }
  }
  index.value++;
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


onMounted(() => {
  window.addEventListener('keydown', handleKeyDown)
  window.addEventListener('keyup', handleKeyUp)
  
})
onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown)
  window.removeEventListener('keyup', handleKeyUp)

})

getList();
</script>
